const { RoleNotFoundError } = require('../../domain/role/error')
const Usecase = require('../../shared/usecase/Usecase')
const R = require('ramda')

class RoleAuthorization extends Usecase {
  constructor({ roleRepo, database, currentUser }) {
    super()
    this.sequelize = database.sequelize
    this.roleRepo = roleRepo
    this.currentUser = currentUser
  }

  async execute(id, data) {
    const role = await this.roleRepo.findById(id, {
      include: ['menuList'],
    })
    if (!role) throw new RoleNotFoundError(id)

    const transaction = await this.sequelize.transaction()
    try {
      await this.roleRepo.updateAuthorization(role, data, {
        transaction,
        currentUser: this.currentUser,
      })
      await transaction.commit()
    } catch (error) {
      await transaction.rollback()
      throw error
    }
  }
}

module.exports = RoleAuthorization
